package com.example.widgetapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.List;

/*getView的加载方法一般有以下三种方式：
1.最慢的加载方式是每一次都重新定义一个View载入布局，再加载数据；
2.正确的加载方式是当convertView不为空时直接重用convertView，从而减少不必要的View的创建；
3.最快的方式是定义一个ViewHolder用于缓存数据实例，将convertView的tag设置为ViewHolder，不为空时重新使用即可。*/


public class MangheAdapterY2 extends ArrayAdapter<Manghe> {

    private final int resourseId;

    public MangheAdapterY2(@NonNull Context context, int resource, @NonNull List<Manghe> objects) {
        super(context, resource, objects);
        this.resourseId = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Manghe manghe = getItem(position);
        View view;
        ViewHolder viewHolder;
        if(convertView == null){
            view = LayoutInflater.from(getContext()).inflate(resourseId,parent,false);
            viewHolder = new ViewHolder();
            viewHolder.mangheImage = view.findViewById(R.id.manghe_image);
            viewHolder.mangheName = view.findViewById(R.id.manghe_name);
            view.setTag(viewHolder);  /*将ViewHolder作为额外数据信息存储到View中*/
        }else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();  /*重新获取ViewHolder*/
        }
        viewHolder.mangheImage.setImageResource(manghe.getImageId());
        viewHolder.mangheName.setText(manghe.getName());
        return view;
    }
    /*ViewHolder是一个静态类，用于保存每行的视图以避免每次调用getView时都调用findViewById()，减少资源映射次数*/
    class ViewHolder{
        ImageView mangheImage;
        TextView mangheName;
    }
}
